<template>
    <div class="app-container">
        <el-row border :gutter="15" class="">
            <el-col :span="7">
                <el-form ref="form" :model="form" :rules="rules" size="small" label-width="130px" label-position="right">
                    <el-form-item label="所属区片：" prop="community_id">
                        <el-select v-model="form.community_id" placeholder="请选择区片" size="small"  >
                            <el-option v-for="(item, index) in communityList" :key="index" :label="item.title"
                                       :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="所属场地：" prop="site_id">
                        <el-select v-model="form.site_id" placeholder="请选择区片" size="small"  >
                            <el-option v-for="(item, index) in siteList" :key="index" :label="item.site_name"
                                       :value="item.site_id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="水机编码" prop="code">
                        <el-input v-model="form.code" placeholder="请输入站点地址"/>
                    </el-form-item>
                    <el-form-item label="水机名称" prop="title">
                        <el-input v-model="form.title" placeholder="请输入站点名称"/>
                    </el-form-item>
                    <el-form-item label="行政区" prop="address">
                        <city-area :clearable="true" :areaSelected="selectedOptions" :defaultProps="areaProps" @area-change="areaChange"></city-area>
                    </el-form-item>
                    <el-form-item label="地址" prop="address">
                        <el-input v-model="form.address" placeholder="请输入站点电话"/>
                    </el-form-item>
                    <el-form-item label="经度" prop="kqLongitude">
                        <el-input v-model="form.lng" placeholder="自动带出" clearable :style="{ width: '100%' }" disabled>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="纬度" prop="kqLatitude">
                        <el-input v-model="form.lat" placeholder="自动带出" clearable :style="{ width: '100%' }" disabled>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="签约日期" prop="signed_at">
                        <el-date-picker
                            v-model="form.signed_at"
                            style="width: 240px"
                            value-format="yyyy-MM-dd"
                            type="date"
                        ></el-date-picker>
                    </el-form-item>
                    <el-form-item label="状态" prop="status">
                        <el-radio-group v-model="form.status">
                            <el-radio
                                v-for="dict in dict.type.sys_normal_disable"
                                :key="dict.value"
                                :label="dict.value"
                            >{{dict.label}}
                            </el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="排序" prop="sort">
                        <el-input-number v-model="form.sort" placeholder="请输入排序"/>
                    </el-form-item>
                    <el-form-item label="备注" prop="remark">
                        <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
                    </el-form-item>

<!--                    <h4 class="form-header h4">骏达系统信息</h4>

                    <el-form-item label="水机名称" prop="mineral_title">
                        <el-input v-model="form.mineral_title" placeholder="请输入水机名称"/>
                    </el-form-item>
                    <el-form-item label="水机名称[富氢水]" prop="rich_title">
                        <el-input v-model="form.rich_title" placeholder="请输入水机名称【富氢水】"/>
                    </el-form-item>

                    <el-form-item label="水机主板id：" prop="equipment_id">
                        <el-select v-model="form.equipment_id" placeholder="请选择区片" size="small"  >
                            <el-option v-for="(item, index) in siteList" :key="index" :label="item.site_name"
                                       :value="item.site_id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="水机主板id[富氢水]：" prop="equipment_id_rich">
                        <el-select v-model="form.equipment_id_rich" placeholder="请选择区片" size="small"  >
                            <el-option v-for="(item, index) in siteList" :key="index" :label="item.site_name"
                                       :value="item.site_id"></el-option>
                        </el-select>
                    </el-form-item>-->
                    <el-form-item style="text-align: center;">
                        <el-button size="small" type="primary" @click="submitForm">保 存</el-button>
                    </el-form-item>
                </el-form>
            </el-col>
            <el-col :span="7">
                <div class="search_box">
                    <div class="label">关键字搜索</div>
                    <el-input v-model="form.address" placeholder="请输入内容" id="tipinput"></el-input>
                </div>
                <div ref="gaode_Map" id="gaode_Map" ></div>
            </el-col>
            <el-col :span="7">
                <el-tabs v-model="currentTab" @tab-click="changeTab">
                    <el-tab-pane
                        :label="item.label"
                        :name="item.value.toString()"
                        v-for="(item, index) in headerList"
                        :key="index"
                    />
                </el-tabs>
                    <el-table v-loading="loadingRead" :data="readList" >
                        <el-table-column label="仪表名称" align="center" prop="end_day" :show-overflow-tooltip="true" />
                        <el-table-column prop="type" label="状态" >
                            <template slot-scope="{row}">
                                <dict-tag :options="dict.type.sys_expenses_master_type" :value="row.type"/>
                            </template>
                        </el-table-column>
                        <el-table-column label="时间" align="center" prop="last_time_number" :show-overflow-tooltip="true" />
                        <el-table-column label="上次读数" align="center" prop="last_time_number" :show-overflow-tooltip="true" />
                        <el-table-column label="本次读数" align="center" prop="now_time_number" :show-overflow-tooltip="true" />
                        <el-table-column label="仪表编码" align="center" prop="" :show-overflow-tooltip="true" />
                    </el-table>
            </el-col>
        </el-row>


    </div>
</template>

<script>

import provincesData from '@/api/data/provinces.json' // 确保路径正确
import { getAllCom} from "@/api/grzq/community.js";

import {getSiteSelectList} from "@/api/system/site";
import {getApparatusDetail,createApparatus,updateApparatus}from "@/api/grzq/apparatus.js";
import AMapLoader from "@amap/amap-jsapi-loader";
import {removeFrom} from "@/utils"; //引入AMapLoader
import { createArea,getListArea } from '@/api/system/areas'
window._AMapSecurityConfig = {
    // 设置安全密钥
    securityJsCode: "2353313c155de6c8befa6921880c92fe",
};

import CityArea from '@/components/CityArea'
export default {
    name: 'site-edit',
    dicts:['sys_normal_disable','sys_expenses_master_type','sys_expenses_master_status'],
    components: {CityArea},
    data() {
        return {
            optionsProvincesList: provincesData, // 直接使用导入的数据
            selectedArea: '',
            select_area_name: '请选择省市区/县',
            selectedOptions: [],
            apparatus_id: '',
            longitude:"",
            latitude:"",
            detailedAddress: "",
            address: "",
            lnglat: [],
            headerList: [
                { label: '水电/详情', value: '1' },
                { label: '物业为', value: '2' },
                { label: '场地费', value: '3' },
            ],
            areaProps: {
                children: '_child',
                label: 'name',
                value: 'id'
            },
            currentTab: '1',
            communityList: [],
            siteList: [],
            cities: [],
            districts: [],

            // 表单参数
            formArea: {},
            form: {},
            input: "",
            map: null,
            autoAMap: null,
            placeSearch: null,
            markers: [],
            position: {},
            AMapPluyins: ["AMap.Geolocation","AMap.AutoComplete", "AMap.PlaceSearch", "AMap.Geocoder","AMap.ControlBar"],
            // 表单校验
            rules: {
                code: [
                    { required: true, message: '站点名称不能为空', trigger: 'blur' }
                ],
                title: [
                    { required: true, message: '站点名称不能为空', trigger: 'blur' }
                ],
                mineral_title: [
                    { required: true, message: '水机名称（骏达系统）不能为空', trigger: 'blur' }
                ],
                rich_title: [
                    { required: true, message: '水机富氢水名称（骏达系统）不能为空', trigger: 'blur' }
                ],
                equipment_id: [
                    { required: true, message: '水机名称（骏达系统）不能为空', trigger: 'blur' }
                ],
                equipment_id_rich: [
                    { required: true, message: '水机富氢水名称（骏达系统）不能为空', trigger: 'blur' }
                ],
                address: [
                    { required: true, message: '站点名称不能为空', trigger: 'blur' }
                ],
                longitude: [
                    { required: true, message: '站点名称不能为空', trigger: 'blur' }
                ],
                latitude: [
                    { required: true, message: '站点名称不能为空', trigger: 'blur' }
                ],
                status: [
                    { required: true, message: '站点名称不能为空', trigger: 'blur' }
                ]
            },

            loadingRead:false,
            readList:[],
        }
    },
    created() {

        this.apparatus_id = this.$route.query && this.$route.query.id;
        const apparatus_id = this.apparatus_id= this.$route.query && this.$route.query.id
        if (apparatus_id!=0) {
            this.getSiteDetail(apparatus_id)
        }else {
            this.selectedOptions=[0,0,0]
            this.initMap()
        }
        this.getAllCom()
        this.getAllSite()
    },
    methods: {
        changeTab() {

        },

        /** 查询 */
        async getSiteDetail(id) {
            this.reset()
            const { data } = await getApparatusDetail({ id: id })
            this.form = data
            this.form.status = data.status.toString()
            this.lnglat = [data.lng,data.lat]
            this.selectedOptions = [data.province_id, data.city_id, data.district_id]
            this.initMap()
        },
        async areaChange(val){
            this.form.province_id = val[0]
            this.form.city_id = val[1]
            this.form.district_id = val[2]
        },
        //片区
        async getAllCom() {
            const res = await getAllCom();
            this.communityList = res.data;
        },
        async getAllSite() {
            const res = await getSiteSelectList();
            this.siteList = res.data;
        },
        /** 查询站点类型列表 */
        async getAreaSelectLists() {
            // const { data } = await getAreaSelectLists()
            this.areaOptions = data
        },
        onChangeProvince() {
            const selectedProvince = this.provinces.find(p => p.code === this.selectedProvince);
            this.cities = selectedProvince.children || [];
            this.selectedCity = this.cities[0]?.code || ''; // 默认选择第一个城市，如果有的话
            this.onChangeCity(); // 更新城市后也需要更新区域列表
        },
        onChangeCity() {
            const selectedCity = this.cities.find(c => c.code === this.selectedCity);
            this.districts = selectedCity?.children || [];
            this.selectedDistrict = this.districts[0]?.code || ''; // 默认选择第一个区域，如果有的话
        },
        /**加载地图*/
        initMap () {
            let centerLen = [116.397428, 39.90923];
            AMapLoader.load({
                key: "86df05c4db672bcbfabc7c71226a5c0a", // 申请好的Web端开发者Key，首次调用 load 时必填
                version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
                plugins: this.AMapPluyins,
            }).then((AMap) => {
                    this.map = new AMap.Map("gaode_Map", {
                        // 设置地图容器id
                        viewMode: "3D", //  是否为3D地图模式
                        zoom: 18, // 初始化地图级别
                        center: centerLen, //中心点坐标
                        resizeEnable: true,
                    });
                    this.setMarker(centerLen)
                    // 关键字查询
                    this.searchMap();
                    // 监听鼠标点击事件
                    this.map.on("click", this.clickMapHandler);
                })
                .catch((e) => { });
        },
        // 关键字查询
        searchMap () {
            // 搜索框自动完成类
            this.autoAMap = new AMap.AutoComplete({
                input: "tipinput", // 使用联想输入的input的id
            });
            //构造地点查询类
            this.placeSearch = new AMap.PlaceSearch({
                map: this.map,
            });
            // 当选中某条搜索记录时触发
            this.autoAMap.on("select", this.selectSite);
        },
        //选中查询出的记录
        selectSite (e) {
            if (e.poi.location) {
                this.placeSearch.setCity(e.poi.adcode);
                this.placeSearch.search(e.poi.name); //关键字查询
                let geocoder = new AMap.Geocoder({});
                let that = this;
                geocoder.getAddress(this.form.lnglat, function (status, result) {
                    console.log('选中查询出的记录',result)
                    if (status === "complete" && result.regeocode) {
                        that.province = result.regeocode.addressComponent.province;
                        that.city = result.regeocode.addressComponent.city;
                        //自己想要赋的值，根据自己的做修改
                        that.$set(that.form, "province", that.province);
                        that.$set(that.form, "city", that.city);
                        that.$set(that.form, "address", e.poi.name);
                        that.$set(
                            that.form,
                            "coordinate",
                            e.poi.location.lng + "," + e.poi.location.lat
                        ); //纬度，经度
                    } else {
                    }
                });
            } else {
                this.$message.error("查询地址失败，请重新输入地址");
            }
        },
        // 点击地图事件获取经纬度，并添加标记
        clickMapHandler (e) {
            this.form.lng = e.lnglat.getLng();
            this.form.lat = e.lnglat.getLat();
            this.lnglat = [e.lnglat.getLng() , e.lnglat.getLat()];

            this.setMarker(this.lnglat);
            // 点击地图上的位置，根据经纬度转换成详细地址
            let geocoder = new AMap.Geocoder({});
            let that = this;
            geocoder.getAddress(this.lnglat, function (status, result) {
                if (status === "complete" && result.regeocode) {
                    that.form.address = result.regeocode.formattedAddress;
                } else {
                }
            });
            this.position = {
                longitude: e.lnglat.getLng(),
                latitude: e.lnglat.getLat(),
                address: that.address,
            };
            this.form.address= that.address; //把查询到的地址赋值到输入框
        },
        //  添加标记
        setMarker (lnglat) {
            this.removeMarker();
            let marker = new AMap.Marker({
                position: lnglat,
            });
            marker.setMap(this.map);
            this.markers.push(marker);
        },
        // 删除之前后的标记点
        removeMarker () {
            if (this.markers) {
                this.map.remove(this.markers);
            }
        },

// 表单重置
        reset() {
            this.form = {
                id: undefined,
                community_id: undefined,
                site_id: undefined,
                type: undefined,
                title: undefined,
                mineral_title: undefined,
                rich_title: undefined,
                equipment_id: undefined,
                equipment_id_rich: undefined,
                code: undefined,
                site_phone: undefined,
                province_id: undefined,
                city_id: undefined,
                district_id: undefined,
                address: undefined,
                lng: undefined,
                lat: undefined,
                signed_at: undefined,
                status: "0",
                sort: 0,
                remark: undefined
            }
            this.resetForm('form')
        },
        // /** 提交按钮 */
        submitForm: function() {
            this.$refs['form'].validate(valid => {
                if (valid) {
                    if (this.form.id != undefined) {
                        updateApparatus(removeFrom(this.form)).then(response => {
                            this.msgSuccess('修改成功')
                            // this.goBack()
                        })
                    } else {
                        this.form.mineral_title = this.form.mineral_title?this.form.mineral_title:this.form.title
                        this.form.rich_title = this.form.rich_title?this.form.rich_title:this.form.title+'富氢水'
                        createApparatus(removeFrom(this.form)).then(response => {
                            this.msgSuccess('新增成功')
                            this.goBack()
                        })
                    }
                }
            })
        },
        /** 返回按钮 */
        goBack() {
            const obj = {
                path: "/sys/site",
                query: {
                    t: Date.now(),
                }
            };
            // this.$tab.closeOpenPage(obj);
            // this.reset();
        },

    }
}
</script>

<style lang="scss">
.search_box {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    height: 50px;

    .label {
        color: #000;
        width: 100px;
    }
}
.content {
    position: relative;
}
#panel {
     position: absolute;
     top: 50px;
     right: 20px;
 }
#gaode_Map {
    overflow: hidden;
    width: 100%;
    height: 500px;
    margin: 0;
}.amap-sug-result {
     z-index: 2999 !important;
 }

</style>
